package org.android.brasil.projetos.oktoberfest2011.view.controller;

import org.android.brasil.projetos.oktoberfest2011.R;
import org.android.brasil.projetos.oktoberfest2011.utils.AnalyticsUtils;
import org.android.brasil.projetos.oktoberfest2011.utils.ControleDeBackground;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.Toast;

/**
 * Com o endereco fornecido traca uma rota ate a vila germanica
 * 
 * @author Henrique Deodato
 * 
 */
public class ComoChegarController extends Activity implements OnClickListener,
		OnLongClickListener, LocationListener, Runnable {
	private static final int ABOUT = Menu.FIRST;

	//mesnagens do handler
	private static final int SHOW_DIALOG = 0;
	private static final int HIDE_DIALOG = 1;
	private static final int ADD_TEXT = 2;
	private static final int SH0W_TOAST = 3;
	
	private Button mComoChgarBtn;
	private EditText mOrigem;
	private EditText mDestino;
	private RadioButton mCarro;
	private RadioButton mPublico;
	private RadioButton mAPe;
	private String mOrigemEndereco;
	private String mDirFlag;
	private LocationManager lm;
	private ImageButton mGetGpsPosBtn;
	private ProgressDialog pdialog;
	private Boolean mLocalizar = true;
	private Thread getGPSThread;

	// cooredandas da vila germanica
	private static final String DESTINO_LAGITUDE = "-26.915981";
	private static final String DESTINO_LONGITUDE = "-49.084028";
	
	private AnalyticsUtils mGa;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		this.mGa = AnalyticsUtils.getInstance(this);
		
		setContentView(R.layout.como_chegar);

		// linka os campos
		mOrigem = (EditText) findViewById(R.id.edt_txt_origem);
		mDestino = (EditText) findViewById(R.id.edt_txt_destino);
		mCarro = (RadioButton) findViewById(R.id.como_chegar_carro);
		mPublico = (RadioButton) findViewById(R.id.como_chegar_publico);
		mAPe = (RadioButton) findViewById(R.id.como_chegar_ape);
		mComoChgarBtn = (Button) findViewById(R.id.como_chegar_button);
		mGetGpsPosBtn = (ImageButton) findViewById(R.id.como_chegar_get_gps);

		mCarro.setOnClickListener(this);
		mPublico.setOnClickListener(this);
		mAPe.setOnClickListener(this);
		mComoChgarBtn.setOnClickListener(this);
		mGetGpsPosBtn.setOnClickListener(this);

		mDestino.setOnLongClickListener(this);

		// get the button and set the click to home...
		ImageView casa = (ImageView) findViewById(R.id.casa);
		casa.setOnClickListener(this);

		RelativeLayout rl = (RelativeLayout) findViewById(R.idMapas.relativeLayout01);
		ControleDeBackground.SetBarraSuperiorBackGround(getApplicationContext(), rl);
		mDirFlag = "";

		// inicia o objeto do GPS
		lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		
		this.mGa.trackScreen(getString(R.string.como_chegar));
	}

	// -------Create the menu-------
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// menu.add(0, ABOUT, 0,
		// R.string.btn_about).setIcon(R.drawable.ic_info);

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (lm != null) {
			lm.removeUpdates(this);
		}
	}

	public boolean onLongClick(View v) {
		switch (v.getId()) {
		case R.id.edt_txt_destino:
			return false;
		default:
			return false;
		}

	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.casa:
			setResult(RESULT_OK);
			finish();
			break;

		// como chegar
		case R.id.como_chegar_button:
			if ((mOrigem.getText().toString().length() == 0)) {

				// put the focus in the title field
				mOrigem.requestFocus();

				// set the error message
				mOrigem.setError(getString(R.string.como_chegar_aviso));
			} else {
				mOrigemEndereco = mOrigem.getText().toString();
				Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri
						.parse("http://maps.google.com/maps?saddr=" + mOrigemEndereco
								+ mDirFlag + "&daddr=" + DESTINO_LAGITUDE + ","
								+ DESTINO_LONGITUDE));

				startActivity(intent);
			}

			break;
		case R.id.como_chegar_ape:
			mDirFlag = "&dirflg=w";
			this.mGa.customTrack("Como Chegar Modo", "a pé");
			break;
		case R.id.como_chegar_carro: // metodo default do maps
			mDirFlag = "";
			this.mGa.customTrack("Como Chegar Modo", "de carro");
			break;
		case R.id.como_chegar_publico:
			mDirFlag = "&dirflg=r";
			this.mGa.customTrack("Como Chegar Modo", "trasnporte público");
			break;
		case R.id.como_chegar_get_gps:
			getGpsLocation();
			break;
		default:

			break;
		}
	}

	public void showLoadingDialog() {
		pdialog = new ProgressDialog(ComoChegarController.this);
		pdialog.setCancelable(true);
		pdialog.setButton("Cancel", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				mLocalizar = false;
				getGPSThread.stop();
			}

		});
		pdialog.setMessage(getString(R.string.gps_loading));
		pdialog.show();
	}

	public void hideLoadingDialog() {
		pdialog.cancel();
		getGPSThread.stop();
	}

	public void getGpsLocation() {
		// exibe o dialog informando sobre a busca da posicao
		showLoadingDialog();

		// inicia a trhead que busca a posicao
		getGPSThread = new Thread(this);
		getGPSThread.start();

	}

	// handle the menu buttons
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent i = null;

		switch (item.getItemId()) {

		case ABOUT:
			i = new Intent(this, SobreController.class);
			startActivity(i);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	// Para controle do GPS
	public void onLocationChanged(Location arg0) {
		// TODO Auto-generated method stub

	}

	public void onProviderDisabled(String arg0) {
		// TODO Auto-generated method stub
		Toast.makeText(this, "Desabilitado", Toast.LENGTH_SHORT).show();
		this.mGa.customTrack("GPS", "desligado");
	}

	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		Toast.makeText(this, "Habilitado", Toast.LENGTH_SHORT).show();
		this.mGa.customTrack("GPS", "ligado");

	}

	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		Toast.makeText(this, "status mudou", Toast.LENGTH_SHORT).show();

	}


	public void run() {
		Message m = new Message();	//mensagem enviada ao handler
		Bundle data = new Bundle(); //envia dados de volta com a mensagem
		Looper.prepare(); // prepara a thread pra rodar...
		
		lm.removeUpdates(this);
		lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 1.0f, this);
		boolean isGPS = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
		if (isGPS) {
			while ((lm.getLastKnownLocation(LocationManager.GPS_PROVIDER) == null)
					&& mLocalizar) {
				// teste...
				try {
					// Evita alto consumo de CPU...eu acho.
					Thread.sleep(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			m.what = HIDE_DIALOG; // hide dialog
			updateHandler.sendMessage(m);
			Location myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

			// Se o usuário cancelar o dialog antes de conseguir a
			// localização
			// tem que verificar se é null ou não.
			if (myLocation != null) {
				String coordenadas = myLocation.getLatitude() + ","
						+ myLocation.getLongitude();
				
				m = new Message();
				data.putString("coordenadas", coordenadas);
				m.setData(data);
				m.what = ADD_TEXT;//atualiza o valor
				updateHandler.sendMessage(m);

				// Toast.makeText(ComoChegarController.this,
				// "posicao ok",
				// Toast.LENGTH_SHORT).show();
			} else {
				m = new Message();
				data.putInt("message", R.string.gps_inativo);
				m.setData(data);
				m.what = SH0W_TOAST;//show toast
				updateHandler.sendMessage(m);
				m = new Message();
				m.what = HIDE_DIALOG;//hide dialog
				updateHandler.sendMessage(m);

			}
		} else {
			m = new Message();
			data.putInt("message", R.string.gps_inativo);
			m.setData(data);
			m.what = SH0W_TOAST;//show toast
			updateHandler.sendMessage(m);
			m = new Message();
			m.what = HIDE_DIALOG;//hide dialog
			updateHandler.sendMessage(m);
		}

	}

	Handler updateHandler = new Handler() {
		/** Gets called on every message that is received */
		// @Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SHOW_DIALOG:
				showLoadingDialog();
				break;
			case HIDE_DIALOG:
				hideLoadingDialog();
				break;
			case ADD_TEXT:
				mOrigem.setText(msg.getData().getString("coordenadas"));
				break;
			case SH0W_TOAST: //show toast messages
				showToast(msg.getData().getInt("message"));
				break;
			}
			super.handleMessage(msg);
		}
	};
	
	public void showToast(int message){
		Toast.makeText(this, message,Toast.LENGTH_SHORT).show();
	}
	
	protected void onDestroy() {
		super.onDestroy();
	}
}